using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

/// <summary>
/// 广告模块管理类
/// 提供OpenHarmony平台广告功能，包括获取OAID、广告加载与展示、静音模式等
/// </summary>
public class AdsKitManager : MonoBehaviour
{
    /// <summary>
    /// OpenHarmony JS对象，用于与原生广告模块交互
    /// </summary>
    public static OpenHarmonyJSObject m_HMSAdsManagerObj { get; private set; } = null;

    /// <summary>
    /// 广告回调事件，用于接收广告操作结果
    /// </summary>
    public static Action<string, string> HMSAdsManagerCallBack = null;

    /// <summary>
    /// OpenHarmony JS回调对象
    /// </summary>
    private static OpenHarmonyJSCallback _hmsAdsManagerCallback;

    /// <summary>
    /// 初始化广告模块
    /// </summary>
    /// <param name="callback">广告操作结果回调，参数为(类型, 数据)</param>
    public static void Init(Action<string, string> callback)
    {
        _hmsAdsManagerCallback = new OpenHarmonyJSCallback(HMSAdsManagerCallback);

        var adsKitManager = new OpenHarmonyJSClass("AdsKitManager");
        m_HMSAdsManagerObj = adsKitManager.CallStatic<OpenHarmonyJSObject>("getInstance");
        Debug.Log($"CreateHMSManager:HMSAdsManagerObj={m_HMSAdsManagerObj}");

        HMSAdsManagerCallBack = callback;
    }

    /// <summary>
    /// 处理来自OpenHarmony的广告回调
    /// </summary>
    /// <param name="args">回调参数，第一个参数为类型，第二个参数为数据</param>
    /// <returns>无返回值</returns>
    private static object HMSAdsManagerCallback(params OpenHarmonyJSObject[] args)
    {
        Debug.Log("HMSAdsManagerCallback: " + args.Length);
        if (args.Length > 0)
        {
            Debug.Log("HMSAdsManagerCallback type: " + args[0].As<string>());
            Debug.Log("HMSAdsManagerCallback data: " + args[1].As<string>());
            HMSAdsManagerCallBack?.Invoke(args[0].As<string>(), args[1].As<string>());
        }
        return null;
    }

    /// <summary>
    /// 获取OAID功能
    /// 用于获取设备的广告标识符
    /// </summary>
    public static void GetOAIDOnUI()
    {
        m_HMSAdsManagerObj.Call("GetOAIDOnUI", _hmsAdsManagerCallback);
    }

    /// <summary>
    /// 加载广告
    /// </summary>
    /// <param name="adId">广告位ID，测试时可使用'testx9dtjwj8hp'</param>
    public static void LoadAdOnUI(string adId)
    {
        m_HMSAdsManagerObj.Call("LoadAdOnUI", adId, _hmsAdsManagerCallback);
    }

    /// <summary>
    /// 展示广告
    /// </summary>
    /// <param name="adIndex">广告索引</param>
    /// <param name="isMute">是否静音模式</param>
    public static void ShowAdOnUI(int adIndex, bool isMute)
    {
        m_HMSAdsManagerObj.Call("ShowAdOnUI", adIndex, isMute, _hmsAdsManagerCallback);
    }
}
